const express=require('express')
const pool=require('../pool')
const router=express.Router()
const authentication=require('./authentication')

// 查询所有菜品
router.get('/list',authentication,(req,res,next)=>{
    pool.query('select * from dish',(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询所有菜品成功',data:r})
    })
})

// 通过id查询菜品
router.get('/queryById',(req,res,next)=>{
    let obj=req.query
    let dishId=obj.dishId
    pool.query('select * from dish where dishId=?',[dishId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'查询指定菜品成功',data:r})
    })
})

// 删除菜品
router.get('/delete',(req,res,next)=>{
    let obj=req.query
    let dishId=obj.dishId
    pool.query('delete from dish where dishId=?',[dishId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'删除菜品成功',data:r})
    })
})

// 增加菜品
router.post('/add',(req,res,next)=>{
    let obj=req.body
    pool.query('insert into dish set ?',[obj],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'增加菜品成功',data:r})

    })
})

// 修改菜品
router.post('/modify',(req,res,next)=>{
    let obj=req.body
    pool.query('update dish set ? where dishId=?',[obj,obj.dishId],(err,r)=>{
        if(err){
            return next(err)
        }
        res.send({code:200,msg:'修改菜品成功',data:r})
    })
})

// 分页查询
router.get('/page',(req,res,next)=>{
    let obj=req.query;
    let pno=obj.pno;
    let pcount=obj.pcount;
    let start =(pno-1)*pcount
    let end =Number(pcount)
    pool.query('select * from dish limit ?,?;select count(*) sum from dish',[start,end],(err,r)=>{
        if(err){
            return next(err)
        }
        let total=r[1][0].sum
        let pages= Math.ceil(total/pcount)
        res.send({code:200,msg:'分页查询成功',pno,pcount,total,pages,data:r})
    })
})

// 查所有菜品数量
router.get('/count',(req,res,next)=>{
    pool.query('select count(*) sum from dish',(err,r)=>{
        if(err){
            return next(err)
        }
        let total=r[0].sum
        res.send({code:200,msg:'查询总菜品数成功',total,data:r})
    })
})
module.exports=router

